<template>
  <div class="page11">
    <el-row>
      <el-col :span="24">
        <div class="title">
          <el-row>
            <el-col :span="18">
              <div class="title-name">{{ title }}</div>
            </el-col>
            <el-col :span="6">
              <div class="action-buttons">
                <button type="button" @click="toggleSelection" class="action-btn delete-btn">
                  <div class="btn-content">
                    <svg t="1755498252837" class="icon" viewBox="0 0 1024 1024" version="1.1" xmlns="http://www.w3.org/2000/svg" p-id="5467" width="20" height="20"><path d="M430.8992 492.1344a32.2048 32.2048 0 0 1-23.8592-10.5472L261.12 321.5872a32.256 32.256 0 0 1 47.6672-43.4688l125.4912 137.5744 341.504-275.1488a32.256 32.256 0 0 1 40.448 50.2272L451.1232 484.9664a32.1536 32.1536 0 0 1-20.224 7.168zM802.5088 912.7424H378.0096a33.536 33.536 0 1 1 0-67.072h424.4992a43.9296 43.9296 0 0 0 43.8784-43.8784V475.3408a33.536 33.536 0 1 1 67.072 0v326.4512a111.104 111.104 0 0 1-110.9504 110.9504z" p-id="5468" fill="#ffffff"></path><path d="M615.424 725.6576H232.192a111.104 111.104 0 0 1-110.9504-110.9504V231.4752a111.104 111.104 0 0 1 110.9504-110.9504H501.76a33.536 33.536 0 0 1 0 67.1232H232.192a43.9296 43.9296 0 0 0-43.8784 43.8784v383.232a43.9296 43.9296 0 0 0 43.8784 43.8784h383.232a43.9296 43.9296 0 0 0 43.8784 43.8784V475.3408a33.536 33.536 0 0 1 67.1232 0v139.3664a111.104 111.104 0 0 1-111.0016 110.9504z" p-id="5469" fill="#ffffff"></path></svg>
                    <span>删除</span>
                  </div>
                </button>
                <button type="button" @click="handleAdd" class="action-btn add-btn">
                  <div class="btn-content">
                    <svg t="1755498312364" class="icon" viewBox="0 0 1024 1024" version="1.1" xmlns="http://www.w3.org/2000/svg" p-id="6511" width="20" height="20"><path d="M544.256 480.256h307.2a32.256 32.256 0 0 1 0 64h-307.2v307.2a32.256 32.256 0 0 1-64 0v-307.2h-307.2a32.256 32.256 0 1 1 0-64h307.2v-307.2a32.256 32.256 0 1 1 64 0z" fill="#ffffff" p-id="6512"></path></svg>
                    <span>添加</span>
                  </div>
                </button>
              </div>
            </el-col>
          </el-row>
        </div>
      </el-col>

      <el-col :span="24">
        <div class="data-container">
          <!-- 数据统计信息 -->
          <div class="data-stats" v-if="total > 0">
            <div class="stat-item">
              <span class="stat-label">总记录数:</span>
              <span class="stat-value">{{ total }}</span>
            </div>
            <div class="stat-item">
              <span class="stat-label">当前页:</span>
              <span class="stat-value">{{ pageNum }}/{{ Math.ceil(total / pageSize) }}</span>
            </div>
          </div>
          
          <!-- 表格容器 -->
          <div class="table-container">
            <el-table
              ref="table"
              @updated="handleTableUpdated"
              :data="tableData"
              style="width: 100%; max-width: 100%;"
              :table-layout="'fixed'"
              :header-cell-style="{ background: '#f5f7fa', color: '#606266', fontSize: '16px', fontWeight: 'bold' }"
              :row-style="{ fontSize: '14px' }"
              :empty-text="loading ? '数据加载中...' : '暂无数据'"
              v-loading="loading"
              element-loading-text="数据加载中..."
              element-loading-spinner="el-icon-loading"
              element-loading-background="rgba(255, 255, 255, 0.8)"
              :border="true"
              :stripe="true"
              :flexible="true"
            >
              <el-table-column type="selection" width="55" align="center" />
              
              <el-table-column
                v-for="(column, index) in columns"
                :key="index"
                :prop="column.prop"
                :label="column.label"
                :width="column.width"
                :min-width="column.minWidth || '120px'"
                :max-width="column.maxWidth || null"
                show-overflow-tooltip
                :resizable="true"
                :align="column.align || 'left'"
              />
              
              <el-table-column label="操作" :width="operationWidth" fixed="right" align="center" min-width="280px">
                <template #default="scope">
                  <div class="action-buttons-cell">
                    <el-button 
                      v-for="(btn, btnIndex) in mergedOperation" 
                      :key="btnIndex"
                      size="small" 
                      :type="btn.type || 'default'"
                      :icon="btn.icon"
                      @click="btn.handler ? btn.handler(scope.$index, scope.row) : handleDefaultAction(btn.action, scope.$index, scope.row)"
                      class="action-cell-btn"
                    >
                      {{ btn.label }}
                    </el-button>
                  </div>
                </template>
              </el-table-column>
            </el-table>
          </div>
          
          <!-- 分页组件 -->
          <div class="pagination-container" v-if="total > 0">
            <div class="pagination-info">
              <span class="pagination-text">
                显示第 {{ (pageNum - 1) * pageSize + 1 }} 至 {{ Math.min(pageNum * pageSize, total) }} 条记录，共 {{ total }} 条
              </span>
            </div>
            <div class="pagination-controls">
              <el-pagination
                @current-change="handlePageChange"
                @size-change="handleSizeChange"
                :current-page="pageNum"
                :page-size="pageSize"
                :page-sizes="[10, 20, 50, 100]"
                :total="total"
                layout="sizes, prev, pager, next, jumper"
                background
                :prev-text="'上一页'"
                :next-text="'下一页'"
                :small="false"
                :hide-on-single-page="false"
                :pager-count="7"
              />
            </div>
            <div class="pagination-actions">
              <el-button 
                size="small" 
                @click="refreshData"
                :loading="loading"
                icon="el-icon-refresh"
                class="refresh-btn"
              >
                刷新
              </el-button>
            </div>
          </div>
          
          <!-- 空状态提示 -->
          <div class="empty-container" v-if="total === 0 && !loading">
            <el-empty description="暂无数据" :image-size="120">
              <el-button type="primary" @click="handleAdd">添加数据</el-button>
            </el-empty>
          </div>
        </div>
      </el-col>
    </el-row>
    
    <!-- 添加农产品对话框 -->
    <el-dialog :title="title" v-model="open" width="500px" append-to-body>
      <el-form :model="form" :rules="rules" label-width="80px">
        <!-- 农产品表单 -->
          <el-form-item label="产品名称" prop="productId">
            <el-select v-if="!permitLoadError && permitProductList.length > 0" v-model="form.productId" placeholder="请选择产品" @change="handleProductChange">
              <el-option 
                v-for="item in permitProductList" 
                :key="item.productId" 
                :label="item.productName" 
                :value="item.productId" 
              />
            </el-select>
            <el-input v-else v-model="form.productId" placeholder="请输入产品ID（准许产品列表加载失败）" />
            <div v-if="permitLoadError" style="color: #f56c6c; font-size: 12px; margin-top: 4px;">
              准许产品列表加载失败，请手动输入产品ID
            </div>
          </el-form-item>
          <el-form-item label="产地" prop="areaId">
            <el-select 
              v-model="form.areaId" 
              placeholder="请选择产地"
              filterable
              :disabled="areaLoadError"
              @change="handleAreaChange"
            >
              <el-option
                v-for="item in areaList"
                :key="item.areaId"
                :label="item.areaName"
                :value="item.areaId"
              />
            </el-select>
            <div v-if="areaLoadError" style="color: #f56c6c; font-size: 12px; margin-top: 4px;">
              产地列表加载失败，请手动输入产地ID
            </div>
          </el-form-item>
          <!-- <el-form-item label="状态" prop="status">
            <el-select v-model="form.status" placeholder="请选择状态">
              <el-option label="正常" value="" />
              <el-option label="禁用" value="0" />
            </el-select>
          </el-form-item> -->
          
          <el-form-item label="计划开始时间" prop="beginTime">
            <el-date-picker clearable
              v-model="form.beginTime"
              type="date"
              value-format="YYYY-MM-DD"
              placeholder="请选择计划开始时间">
            </el-date-picker>
          </el-form-item>
          <el-form-item label="计划结束时间" prop="reapTime">
            <el-date-picker clearable
              v-model="form.reapTime"
              type="date"
              value-format="YYYY-MM-DD"
              placeholder="请选择计划结束时间">
            </el-date-picker>
          </el-form-item>
          <el-form-item label="作物昵称" prop="cropName">
            <el-input v-model="form.cropName" placeholder="请输入作物昵称" />
          </el-form-item>
         
          <el-form-item label="产量单位" prop="yieldUnit">
            <el-select v-model="form.yieldUnit" placeholder="请选择产量单位">
              <el-option label="吨" value="吨" />
              <el-option label="千斤" value="千斤" />
              <el-option label="斤" value="斤" />
            </el-select>
          </el-form-item>
           <el-form-item label="预计总产量" prop="estimatedTotalYield">
            <el-input v-model="form.estimatedTotalYield" placeholder="请输入预计总产量" />
          </el-form-item> 
          <el-form-item label="种植面积" prop="plantingAravage">
            <el-input v-model="form.plantingAravage" placeholder="请输入种植面积" />
          </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, defineProps, defineEmits, reactive, computed, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { addProduct } from '@/api/ncpsy/management/product'
import { addArea, listArea } from '@/api/ncpsy/management/area'
import { addEvent } from '@/api/ncpsy/management/event'
import { listPermit } from '@/api/ncpsy/management/permit'
import { useRouter } from 'vue-router'
import useUserStore from '@/store/modules/user'
const router = useRouter()
const userStore = useUserStore()

// 加载状态
const loading = ref(false)

// 操作列宽度计算
const operationWidth = computed(() => {
  // 根据操作按钮数量动态计算宽度，但限制最大宽度
  const baseWidth = 20
  const buttonWidth = 80 // 减少按钮宽度
  const buttonCount = mergedOperation.value.length
  // 每个按钮之间有间隔，增加额外空间
  const spacingWidth = Math.max(0, (buttonCount - 1) * 8)
  // 确保最小宽度，并为每个按钮提供足够空间
  const calculatedWidth = baseWidth + buttonWidth * buttonCount + spacingWidth
  // 增加额外缓冲空间，确保按钮不会被挤压
  const bufferSpace = 20
  // 设置最大宽度为300px，最小宽度为200px
  return Math.min(Math.max(calculatedWidth + bufferSpace, 200), 300) + 'px'
})

const props = defineProps({
  title: {
    type: String,
    default: '种植地列表'
  },
  columns: {
    type: Array,
    
  },
  tableData: {
    type: Array,
    
  },
  operation: {
    type: Array,
    default: () => []
  },
  // 分页相关props
  total: {
    type: Number,
    default: 0
  },
  pageNum: {
    type: Number,
    default: 1
  },
  pageSize: {
    type: Number,
    default: 10
  }
})

const emit = defineEmits(['add', 'edit', 'delete', 'refresh', 'page-change', 'size-change'])
const table = ref(null)
const showSelection = ref(false)
const open = ref(false)
const title = ref(props.title);
const currentApi = ref('product') // 当前使用的API类型
const permitProductList = ref([]) // 准许产品列表
const permitLoadError = ref(false) // 准许产品列表加载失败标志
const areaList = ref([]) // 产地列表
const areaLoadError = ref(false) // 产地列表加载失败标志

// 默认的操作按钮配置
const defaultOperation = ref([
  { label: '修改', action: 'edit', type: 'primary' },
  { label: '删除', action: 'delete', type: 'danger' }
])

// 合并传入的operation和默认按钮
const mergedOperation = computed(() => {
  return [...defaultOperation.value, ...props.operation]
})

const data = reactive({
  form: {
    productId: null,
    areaId: null,
    userId: userStore.id,
    status: null,
    beginTime: null,
    reapTime: null,
    cropName: null,
    estimatedTotalYield: null,
    totalYield: null,
    yieldUnit: null,
    plantingAravage: null,
    hash: null
  },
  rules: {
    // 通用规则
    status: [
      { required: true, message: "状态不能为空", trigger: "change" }
    ],
    userId: [
      { required: true, message: "用户ID不能为空", trigger: "blur" }
    ],
    
    // 农产品特定规则
    beginTime: [
      { required: true, message: "计划开始时间不能为空", trigger: "blur" }
    ],
    estimatedTotalYield: [
      { required: true, message: "预计总产量不能为空", trigger: "blur" }
    ],
    yieldUnit: [
      { required: true, message: "产量单位不能为空", trigger: "change" }
    ],
    
    // 种植地特定规则
    userCode: [
      { required: true, message: "所属用户编号不能为空", trigger: "blur" }
    ],
    areaName: [
      { required: true, message: "产地名称不能为空", trigger: "blur" }
    ],
    areaAddress: [
          { required: true, message: "产地地点不能为空", trigger: "blur" }
        ],
    areaAcreage: [
      { required: true, message: "产地面积不能为空", trigger: "blur" }
    ],
    acreageKind: [
      { required: true, message: "面积单位不能为空", trigger: "change" }
    ],
    landKind: [
      { required: true, message: "土壤类型不能为空", trigger: "change" }
    ],
    areaStatus: [
      { required: true, message: "产地状态不能为空", trigger: "change" }
    ],
    responsiblePerson: [
      { required: true, message: "土地负责人不能为空", trigger: "blur" }
    ],
    contactPhone: [
      { required: true, message: "联系电话不能为空", trigger: "blur" }
    ],
    
    // 事件特定规则
    cropEventId: [
      { required: true, message: "事件ID不能为空", trigger: "blur" }
    ],
    eventSummary: [
      { required: true, message: "事件总述不能为空", trigger: "blur" }
    ],
    eventStartTime: [
      { required: true, message: "事件起始时间不能为空", trigger: "blur" }
    ],
    eventEndTime: [
      { required: true, message: "事件结束时间不能为空", trigger: "blur" }
    ],
    overallStatus: [
      { required: true, message: "总状态不能为空", trigger: "change" }
    ],
    remark: [
      { required: true, message: "备注不能为空", trigger: "blur" }
    ]
  }
})

const { form, rules } = toRefs(data)

const handleTableUpdated = () => {
  table.value?.doLayout()
}

// 处理分页变化
const handlePageChange = (page) => {
  loading.value = true
  emit('page-change', page)
  // 模拟加载完成，实际应该由父组件控制
  setTimeout(() => {
    loading.value = false
  }, 500)
}

// 处理每页条数变化
const handleSizeChange = (size) => {
  loading.value = true
  emit('size-change', size)
  // 模拟加载完成，实际应该由父组件控制
  setTimeout(() => {
    loading.value = false
  }, 500)
}

const toggleSelection = () => {
  showSelection.value = !showSelection.value
}

const handleAdd = () => {
  if (props.title.includes('种植地')) {
    router.push('/zspt/Page1Vue')
  } else if (props.title.includes('农产品')) {
    router.push('/zspt/AddProduct')
  }
}

const handleEdit = (index, row) => {
  emit('edit', { index, row })
}

const handleDelete = (index, row) => {
  emit('delete', { index, row })
}

// 加载准许产品列表
const loadPermitProducts = async () => {
  try {
    const query = {
      auditStatus: '审核通过', // 审核状态为审核通过
      userId: userStore.id // 当前用户ID
    }
    const response = await listPermit(query)
    console.log('获取准许产品列表:', response)
    // 假设返回的数据在rows数组中
    if (response.rows && response.rows.length > 0) {
      permitProductList.value = response.rows.map(item => ({
        productId: item.productId,
        productName: item.productName
      }))
    } else {
      permitProductList.value = []
      ElMessage.warning('暂无审核通过的准许产品')
    }
  } catch (error) {
    console.error('获取准许产品列表失败:', error)
    ElMessage.error('获取准许产品列表失败: ' + (error.message || '未知错误'))
    permitProductList.value = []
    permitLoadError.value = true
  }
}

// 获取产地列表
const loadAreaList = async () => {
  try {
    console.log('当前用户ID:', userStore.id)
    const queryParams = {
      pageNum: 1,
      pageSize: 100, // 获取所有产地数据
      userId: userStore.id,
      areaStatus: '在用' // 只获取状态为"在用"的产地
    }
    const response = await listArea(queryParams)
    if (response.code === 200) {
      areaList.value = response.rows
    } else {
      areaLoadError.value = true
    }
  } catch (error) {
    console.error('加载产地列表失败:', error)
    areaLoadError.value = true
  }
}

// 产地选择变化处理
const handleAreaChange = (areaId) => {
  console.log('选择产地ID:', areaId)
  const selectedArea = areaList.value.find(item => item.areaId === areaId)
  if (selectedArea) {
    console.log('选择产地名称:', selectedArea.areaName)
  }
}

// 默认按钮动作处理
const handleDefaultAction = (action, index, row) => {
  switch (action) {
    case 'edit':
      handleEdit(index, row)
      break
    case 'delete':
      handleDelete(index, row)
      break
    case 'completeArchive':
      // 完善档案 - 跳转路由
      console.log('完善档案:', row)
      ElMessage.info('跳转到档案完善页面，档案ID: ' + row.id)
      break
    case 'createArchive':
      // 创建档案 - 弹窗确认
      ElMessageBox.confirm(
        '确定要为此农产品创建档案吗？',
        '创建档案确认',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }
      ).then(() => {
        console.log('创建档案:', row)
        ElMessage.success('档案创建成功！')
      }).catch(() => {
        ElMessage.info('已取消创建')
      })
      break
    case 'recordEvent':
      // 记录事件处理
      console.log('记录事件:', row)
      ElMessage.info('记录事件功能，农产品ID: ' + row.cropEventId)
      //跳转页面到种植管理，携带cropEventId和overallStatus参数
      router.push({
        path: '/zspt/Page3Vue',
        query: {
          cropEventId: row.cropEventId,
          overallStatus: row.overallStatus
        }
      })
      break
    case 'recordEventbyCropId':
      // 根据作物ID查看事件处理
      console.log('根据作物ID查看事件:', row)
      ElMessage.info('查看作物相关事件，作物ID: ' + row.cropId)
      // 跳转到事件列表页面，携带cropId参数
      router.push({
        path: '/zspt/Page13Vue',
        query: {
          cropId: row.cropId
        }
      })
      break
    default:
      console.log('未知动作:', action, row)
  }
}

// 刷新数据
const refreshData = () => {
  loading.value = true
  emit('refresh')
  // 模拟加载完成，实际应该由父组件控制
  setTimeout(() => {
    loading.value = false
  }, 500)
}

// 组件挂载时加载数据
onMounted(() => {
  // 如果需要，可以在这里加载初始数据
})
</script>

<style scoped>
.page11 {
  padding: 20px;
  background-color: #f5f7fa;
  min-height: calc(100vh - 84px);
}

.title {
  margin: 0 0 20px 0;
  line-height: 60px;
  background: linear-gradient(135deg, #4caf50 0%, #2e7d32 100%);
  border-radius: 12px;
  box-shadow: 0 4px 12px rgba(46, 125, 50, 0.2);
  padding: 0 20px;
}

.title-name {
  font-size: 24px;
  color: white;
  font-weight: bold;
  text-align: left;
}

.action-buttons {
  display: flex;
  justify-content: flex-end;
  gap: 12px;
  height: 60px;
  align-items: center;
}

.action-btn {
  width: 100px;
  height: 36px;
  border: none;
  border-radius: 8px;
  cursor: pointer;
  transition: all 0.3s ease;
  box-shadow: 0 2px 6px rgba(0, 0, 0, 0.1);
}

.delete-btn {
  background-color: #f44336;
}

.delete-btn:hover {
  background-color: #d32f2f;
  transform: translateY(-2px);
  box-shadow: 0 4px 8px rgba(244, 67, 54, 0.3);
}

.add-btn {
  background-color: #4caf50;
}

.add-btn:hover {
  background-color: #388e3c;
  transform: translateY(-2px);
  box-shadow: 0 4px 8px rgba(76, 175, 80, 0.3);
}

.btn-content {
  display: flex;
  justify-content: center;
  align-items: center;
  color: white;
  font-size: 14px;
  gap: 6px;
}

.data-container {
  background: white;
  border-radius: 12px;
  box-shadow: 0 4px 20px rgba(0, 0, 0, 0.08);
  overflow: hidden;
  padding: 20px;
}

.data-stats {
  display: flex;
  justify-content: flex-end;
  gap: 24px;
  margin-bottom: 16px;
  padding: 12px 16px;
  background-color: #f8f9fa;
  border-radius: 8px;
}

.stat-item {
  display: flex;
  align-items: center;
  gap: 6px;
}

.stat-label {
  font-size: 14px;
  color: #606266;
}

.stat-value {
  font-size: 16px;
  font-weight: bold;
  color: #2e7d32;
}

.table-container {
  margin-bottom: 20px;
  border-radius: 8px;
  overflow: hidden;
  width: 100%;
  max-width: 100%;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);
}

/* 确保表格不超出容器宽度 */
:deep(.el-table) {
  width: 100% !important;
  max-width: 100% !important;
  table-layout: fixed !important;
}

/* 确保表格单元格不会溢出 */
:deep(.el-table .cell) {
  word-break: break-all;
  white-space: normal;
  overflow: hidden;
  text-overflow: ellipsis;
}

/* 操作列特殊处理 */
:deep(.el-table .el-table__fixed-right) {
  right: 0 !important;
}

/* 响应式设计优化 */
@media (max-width: 1200px) {
  .table-container {
    overflow-x: auto;
  }
  
  :deep(.el-table) {
    min-width: 100%;
  }
  
  .action-cell-btn {
    padding: 4px 8px;
    font-size: 11px;
  }
  
  :deep(.el-table__body td .cell) {
    padding: 0 8px;
    font-size: 13px;
  }
}

@media (max-width: 992px) {
  .table-container {
    overflow-x: auto;
  }
  
  :deep(.el-table) {
    min-width: 800px;
  }
}

@media (max-width: 768px) {
  .page11 {
    padding: 10px;
  }
  
  .title {
    line-height: 50px;
    padding: 0 15px;
  }
  
  .title-name {
    font-size: 20px;
  }
  
  .action-buttons {
    gap: 8px;
  }
  
  .action-btn {
    width: 80px;
    height: 32px;
  }
  
  .btn-content {
    font-size: 12px;
  }
  
  .data-container {
    padding: 15px;
  }
  
  .data-stats {
    flex-direction: column;
    gap: 8px;
  }
  
  :deep(.el-table__body td .cell) {
    padding: 0 6px;
    font-size: 12px;
  }
  
  .action-cell-btn {
    padding: 3px 6px;
    font-size: 10px;
  }
  
  .pagination-container {
    flex-direction: column;
    gap: 12px;
  }
  
  .pagination-controls {
    order: 2;
    width: 100%;
  }
  
  .pagination-info {
    order: 1;
    width: 100%;
    text-align: center;
  }
  
  .pagination-actions {
    order: 3;
    width: 100%;
    justify-content: center;
  }
}

@media (max-width: 576px) {
  .action-buttons-cell {
    flex-direction: column;
    gap: 4px;
  }
  
  .action-cell-btn {
    width: 100%;
    margin: 0;
  }
  
  .table-container {
    overflow-x: scroll;
    -webkit-overflow-scrolling: touch;
  }
  
  :deep(.el-table) {
    min-width: 600px;
  }
}

@media (max-width: 480px) {
  .action-buttons {
    flex-direction: column;
    height: auto;
    padding: 10px 0;
  }
  
  .action-btn {
    width: 100%;
  }
  
  .title-name {
    font-size: 18px;
  }
  
  .data-container {
    padding: 10px;
  }
  
  .stat-item {
    padding: 6px 12px;
  }
  
  .stat-value {
    font-size: 16px;
  }
}
</style>